const Service = require('egg').Service;

class ArticleTypeService extends Service {

  /**
   * @description 通过id寻找
   * @author xiezuobing[948466]<435321508@qq.com>
   * @param {any} articleTypeId 
   * @returns  
   * @memberof ArticleTypeService
   */
  async selectById(articleTypeId){
    return await this.ctx.model.ArticleType.findById(articleTypeId);
  }

  /**
   * @description 根据类型名搜索
   * @author xiezuobing[948466]<435321508@qq.com>
   * @param {any} articleTypeName 
   * @returns  
   * @memberof ArticleTypeService
   */
  async selectByName(articleTypeName) {
    const ctx = this.ctx;
    return await ctx.model.ArticleType.findOne({
      where: {
        name: articleTypeName,
        parent_id: 0
      },
      include: [{
        model: ctx.model.ArticleType,
        as: 'children',
        include: [{
          model: ctx.model.Article,
          as: 'articles',
          // include: [{
          //   model: ctx.model.Resource,
          //   as: 'file',
          // }],
        }],
      }],
    });
  }

  /**
   * @description 查询文章类型列表
   * @author xiezuobing[948466]<435321508@qq.com>
   * @param {number} [parentId=0] 
   * @returns  
   * @memberof ArticleTypeService
   */
  async list(parentId = 0) {
    const ctx = this.ctx;
    return await ctx.model.ArticleType.findAll({
        where: {
          parent_id: parentId
        },
        include: [{
          model: ctx.model.ArticleType,
          as: 'children',
          include: [{
            model: ctx.model.ArticleType,
            as: 'children'
          }],
        }],
      });
  }

  /**
   * @description 删除改机分类及下级分类
   * @author xiezuobing[948466]<435321508@qq.com>
   * @param {any} articleTypeId 
   * @returns  
   * @memberof ArticleTypeService
   */
  async delete(articleTypeId) {
    return await this.ctx.model.ArticleType.destroy({
        where: {
          $or: [{
            id: articleTypeId
          }, {
            parent_id: articleTypeId
          }, {
            grand_parent_id: articleTypeId
          }]
        }
      })
  }

  /**
   * @description 增加
   * @author xiezuobing[948466]<435321508@qq.com>
   * @param {any} values 
   * @returns  
   * @memberof ArticleTypeService
   */
  async create(values) {

    return await this.ctx.model.ArticleType.create(values);
  }

  /**
   * @description 更新
   * @author xiezuobing[948466]<435321508@qq.com>
   * @param {any} values 
   * @returns  
   * @memberof ArticleTypeService
   */
  async update(values) {
    return await this.ctx.model.ArticleType.update(values, {
        where: {
          id: values.id
        }
      })
  }
}

module.exports = ArticleTypeService;